package org.example.minebackend.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.minebackend.mapper.CommunityMapper;
import org.example.minebackend.mapper.PersonCenterMapper;
import org.example.minebackend.pojo.Comment;
import org.example.minebackend.pojo.Invitation;
import org.example.minebackend.pojo.PageBean;
import org.example.minebackend.pojo.User;
import org.example.minebackend.pojo.dto.CommentDTO;
import org.example.minebackend.pojo.dto.InvitationDTO;
import org.example.minebackend.pojo.dto.InvitationDetailDTO;
import org.example.minebackend.pojo.dto.InvitationPageDTO;
import org.example.minebackend.service.CommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommunityServiceImpl implements CommunityService {
    @Autowired
    CommunityMapper communityMapper;
    @Autowired
    private PersonCenterMapper personCenterMapper;

    public PageBean getInvitations(InvitationPageDTO invitationPage) {
        Integer page = invitationPage.getPage();  // 当前页
        Integer pageSize = invitationPage.getPageSize(); // 每页大小
        String kind = invitationPage.getKind();   // 类型筛选
        String content = invitationPage.getContent(); // 内容筛选
        String orderType = invitationPage.getOrderType(); // 排序方式

        // 启动分页（使用PageHelper进行分页）
        PageHelper.startPage(page, pageSize);

        // 执行查询
        List<Invitation> invitationList = communityMapper.getInvitations(kind, orderType, content);

        // 查找每个帖子的作者姓名并转化为DTO
        List<InvitationDTO> invitationDTOList = new ArrayList<>();
        for (Invitation invitation : invitationList) {
            User user = personCenterMapper.getMessage(invitation.getWriterId());
            InvitationDTO invitationDTO = new InvitationDTO(invitation, user.getUsername());
            invitationDTOList.add(invitationDTO);
        }

        // 使用PageHelper返回的Page对象
        Page<Invitation> invitationsPage = (Page<Invitation>) invitationList; // 这里应该获取 Page<Invitation> 对象

        // 创建一个新的 Page<InvitationDTO> 对象，并传入转换后的列表及分页信息
        Page<InvitationDTO> resultPage = new Page<InvitationDTO>(page, pageSize);
        resultPage.addAll(invitationDTOList);
        resultPage.setTotal(invitationsPage.getTotal()); // 设置总记录数

        // 创建 PageBean 返回结果
        PageBean pageBean = new PageBean((int) resultPage.getTotal(), resultPage);
        return pageBean;
    }

    public int uploadInvitation(Invitation invitation) {
        int result = 0;
        // 先通过id获取作者的姓名
        User user = personCenterMapper.getMessage(invitation.getWriterId());
        if(user == null){ return -1;}
//        invitation.setWriter(user.getUsername());
        try {
            result = communityMapper.uploadInvitation(invitation);
        } catch (Exception e) {
            result = -1;
        }
        return result;
    }

    public InvitationDetailDTO getInvitationById(Integer id) {
        // 通过文章id查询文章信息，在通过writerId查询作者信息
        Invitation invitation = communityMapper.getInvitationById(id);
        // 查询作者姓名
        User user = personCenterMapper.getMessage(invitation.getWriterId());
        InvitationDetailDTO invitationDetailDTO = new InvitationDetailDTO(invitation, user.getUsername(), user.getImage());
        return invitationDetailDTO;
    }

    public List<CommentDTO> getAllCommentByInvitationId(Integer id) {
        List<Comment> comments = communityMapper.getAllCommentByInvitationId(id);
        // 先找一级评论，一级评论的父评论id为-1
        List<Comment> rootComments = comments.stream().filter(comment -> comment.getParentId() == -1).toList();
        // 找一级评论的全部子评论
        for (Comment rootComment : rootComments) {
            rootComment.setChildrenComment(comments.stream().filter(comment -> rootComment.getId() == (comment.getRootId())).collect(Collectors.toList()));
        }
        // 将comment转换为commentDTO
        List<CommentDTO> rootCommentDTOs = new ArrayList<>();
        for (Comment rootComment : rootComments) {
            CommentDTO commentDTO = new CommentDTO();
            // 通过userId查找信息
            User user = personCenterMapper.getMessage(rootComment.getUserId());
//            User targetUser = personCenterMapper.getMessage(rootComment.getParentId());
            commentDTO.setId(rootComment.getId());
            commentDTO.setContent(rootComment.getContent());
            commentDTO.setUsername(user.getUsername());
            commentDTO.setImage(user.getImage());
            commentDTO.setTargetUserId(-1);

//            commentDTO.setTargetUserName(targetUser.getUsername());
            commentDTO.setCreateTime(rootComment.getCreateTime());
            List<CommentDTO> childrenCommentDTOs = new ArrayList<>();
            for (Comment comment : rootComment.getChildrenComment()) {
                CommentDTO childCommentDTO = new CommentDTO();
                User user1 = personCenterMapper.getMessage(comment.getUserId());
                // 寻找回复对象的name
                Comment parent = communityMapper.getCommentByInvitationId(comment.getParentId());
                User targetUser1 = personCenterMapper.getMessage(parent.getUserId());
                childCommentDTO.setId(comment.getId());
                childCommentDTO.setContent(comment.getContent());
                childCommentDTO.setUsername(user1.getUsername());
                childCommentDTO.setTargetUserName(targetUser1.getUsername());
                childCommentDTO.setTargetUserId(targetUser1.getId());
                childCommentDTO.setImage(user1.getImage());
                childCommentDTO.setCreateTime(comment.getCreateTime());
                childrenCommentDTOs.add(childCommentDTO);
            }
            commentDTO.setChildComment(childrenCommentDTOs);
            rootCommentDTOs.add(commentDTO);
        }
        return rootCommentDTOs;
    }

    public int uploadComment(Comment comment) {
        int result = 0;
        try {
            result = communityMapper.uploadComment(comment);
        } catch (Exception e) {
            result = -1;
        }

        return result;
    }

    public int addInvitationOfCollection(Integer userId, Integer invitationId) {
        int n = communityMapper.judgeCollection(userId, invitationId);
        if(n == 0) {
            communityMapper.addInvitationCollectionById(invitationId);

            communityMapper.insertInvitationOfCollectionById(userId, invitationId);
        }
        return n;
    }

    public int judgeCollection(Integer userId, Integer invitationId) {
        return communityMapper.judgeCollection(userId, invitationId);
    }

    public int deleteCollection(Integer userId, Integer invitationId) {
        int n = communityMapper.judgeCollection(userId, invitationId);
        if(n == 1) {
            communityMapper.deleteInvitationCollectionById(invitationId);
            communityMapper.deleteInvitationCollectionByTwoId(userId, invitationId);
        }
        return n;
    }
}
